package cn.com.controller;

import cn.com.Authorization;
import cn.com.beans.PAccount;
import cn.com.beans.PResource;
import cn.com.beans.PRole;
import cn.com.beans.UserInfo;
import cn.com.consts.SystemConst;
import cn.com.service.PAccountService;
import cn.com.service.RoleService;
import cn.com.service.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLOutput;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/account")
@SessionAttributes({SystemConst.LOGIN_STATUS,SystemConst.MENUS})

public class AccountContorller implements BaseController {
    @Resource
    private PAccountService accountService;

    @Resource
    private RoleService roleService;

    @Resource
    private UserInfoService userInfoService;

    @GetMapping
    @Authorization(url="/account",authority="r",methods=RequestMethod.GET)
    public String home() {
        System.out.println(getModelName());
        return getModelName()+"/index";
    }

    @GetMapping("index")
    @Authorization(url="/account",authority="r",methods=RequestMethod.GET)
    public String home1() {
        return "/index";
    }

    @Override
    public String getModelName() {
        return "account";
    }

    @GetMapping("/login")
    public String login(){
        return "login2";
    }

    @PostMapping("/login")
    public String login(String account, ModelMap model, HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println("进入login");
        PAccount paccount = new PAccount();
        paccount.setAccount(account);
        List<PAccount> accounts = accountService.findAll(paccount);
        if(accounts.size()==1){
            System.out.println("找到账号");
            PAccount account1 = accounts.get(0);
            List<PResource> resources = account1.getResource();
            System.out.println(resources);
            Map<Integer,List<PResource>> menus =new HashMap<>();
            for(PResource resource:resources){
                if (resource.getType() == 1){
                    if(!menus.containsKey(resource.getPid())){
                        menus.put(resource.getPid(),new ArrayList<>());
                    }
                    menus.get(resource.getPid()).add(resource);
                }
            }
//            model.addAttribute(SystemConst.MENUS,menus);
//            model.addAttribute(SystemConst.LOGIN_STATUS,account);
            session.setAttribute("uaid",account1.getId());
            UserInfo userInfo = userInfoService.selectByPrimaryKey(account1.getId());
            session.setAttribute("name", userInfo.getUName());
            session.setAttribute(SystemConst.LOGIN_STATUS,account);
            session.setAttribute(SystemConst.MENUS,menus);
        }else{
            System.out.println(1);
            return "login2";
        }
        System.out.println(2);
        return "redirect:/";
    }

    @GetMapping(headers = "X-Requested-With=XMLHttpRequest")
    @ResponseBody
    @Authorization(url = "/account",authority = "r",methods = RequestMethod.GET)
    public Map<String,Object> findAll(PAccount account,@RequestParam(defaultValue = "0")int page
            ,@RequestParam(defaultValue = "10")int limit){
        PageHelper.startPage(page,limit);
        List<PAccount> accounts = accountService.findAll(account);
        PageInfo<PAccount> pageInfo = new PageInfo<>(accounts);
        Map<String,Object> result = new HashMap<>();
        result.put("data",pageInfo.getList());
        result.put("code",0);
        result.put("count",pageInfo.getTotal());
        result.put("msg","查询成功");
        return result;
    }
    @GetMapping({"/edit","/edit/{id}"})
    @Authorization(url = "/account/edit",authority = "r",methods = RequestMethod.GET)
    public String editor(@PathVariable(required = false) Integer id,Model model){
        if(id != null){
            PAccount byId = this.accountService.findById(id);
            model.addAttribute("account",byId);
        }
        return getModelName()+"/editor";
    }
    @PutMapping
    @ResponseBody
    @Authorization(url = "/account",authority = "c,u",methods = RequestMethod.PUT)
    public Map<String,Object> save(PAccount account,@RequestParam("roleIds[]") Integer[] roleIds){
        System.out.println("ok");
        Map<String,Object> results = new HashMap<>();
        if(account.getId()!= null){
            try {
                accountService.updateAcount(account,roleIds);
                results.put("code",0);
                results.put("msg","修改成功");
            }catch (Exception e){
                e.printStackTrace();
                results.put("code",1);
                results.put("msg","修改失败:"+e.getMessage());
            }
        }else{
            try {
                accountService.insertAccount(account,roleIds);
                results.put("code",0);
                results.put("msg","新增成功");
            }catch (Exception e){
                e.printStackTrace();
                results.put("code",1);
                results.put("msg","新增失败:"+e.getMessage());
            }
        }
        return results;
    }




    @DeleteMapping
    @ResponseBody
    @Authorization(url = "/account",authority = "d",methods = RequestMethod.DELETE)
    public Map<String,Object> delete(@RequestParam("id") Integer[] ids){
        Map<String,Object> resoult = new HashMap<>();
        if(accountService.deleteByIds(ids)){
            resoult.put("code",0);
            resoult.put("msg","删除成功");
        }else {
            resoult.put("code",1);
            resoult.put("msg","删除失败");
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return resoult;
    }
    @GetMapping({"/role/{accountId}","/role"})
    @Authorization(url = "/account/role",authority = "r",methods = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object>> findRole(@PathVariable(required = false) Integer accountId){
        List<PRole> roles = roleService.findAll(null);
        Set<Integer> roleIds = null;
        if(accountId != null){
            PAccount account = this.accountService.findById(accountId);
            List<PRole> selectRoles = account.getRoles();
            roleIds = selectRoles.stream().map(role -> role.getId()).collect(Collectors.toSet());
        }
        //将角色ID取出并构建成Set集合
        List<Map<String,Object>> roleList = new ArrayList<>();
        for(PRole role:roles){
            Map<String,Object> roleMap = new HashMap<>();
            roleMap.put("name",role.getName());
            roleMap.put("value",role.getId());
            roleMap.put("selected",roleIds!=null?roleIds.contains(role.getId()):false);
            roleList.add(roleMap);

        }
        return roleList;
    }




}
